package com.springbooti18n.validate.response;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * xufan
 * 2019/1/6
 */
//@Aspect
//@Component
@ControllerAdvice
public class i18nAspect implements ResponseBodyAdvice {
    @Resource
    ResourceBundleMessageSource messageSource;


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        I18n i18n = returnType.getMethodAnnotation(I18n.class);;
         if(i18n==null){
             return false;
         }else{
             return true;
         }

    }

    @Override
    public Object beforeBodyWrite(
            Object body, MethodParameter returnType,MediaType selectedContentType,
            Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        I18n i18n = returnType.getMethodAnnotation(I18n.class);
        String basename = i18n.baseName();
        String[] messageKeys = i18n.messageKeys();
        if(messageKeys!=null && messageKeys.length>0){
           List<String> messages = Arrays.asList(messageKeys);
            messageSource.setBasenames(basename);
            for(String key : messages){
                String message = messageSource.getMessage(key,
                        null, LocaleContextHolder.getLocale());
//        修改body中需要国际化的东东
                System.out.println(message);
            }
        }

        return body;
    }
}
